const md5 = require('md5');
const multer = require('koa-multer');

const tools = {
	
	/**
	 * md5加密
	 */
	md5 (str) {
		return md5(str);
	},
	
	/**
	 * 数据转分类list
	 */
	cateToList(data) {
		let firstArr = [];
		
		for(let i = 0; i < data.length; i++){
			if(!data[i].pid || data[i].pid === '0'){
				firstArr.push(data[i]);
			}
		}
		
		for (let i = 0; i < firstArr.length; i++){
			firstArr[i].children = [];
			for(let j = 0; j < data.length; j++){
				if(firstArr[i]._id == data[j].pid){
					firstArr[i].children.push(data[j]);
				}
			}
		}
		
		return firstArr;
	},
	
	/**
	 * 图片上传封装
	 */
	multer(){
		// 配置图片上传目录
		const storage = multer.diskStorage({
			destination: function(req, file, cb){
				cb(null, 'static/upload')
			},
			filename: function(req, file, cb){
				let fileFormat = (file.originalname).split('.');
		
				// 需要处理上传的文件命名（这里要填上后缀，不然koa-multer会丢失后缀名）
				cb(null, file.fieldname + '-' + Date.now() + '.' + fileFormat[fileFormat.length - 1]);
		
				//cb(null, file.fieldname + '-' + Date.now())
			}
		});
		const upload = multer({storage: storage});
		
		return upload;
	}
};

module.exports = tools;
